package so.shanku.essential.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import cn.jpush.android.api.JPushInterface;
import com.lidroid.xutils.BitmapUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.network.NetWorkHelper;
import net.tsz.afinal.toast.Toast;
import so.shanku.essential.R;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetServicesDataUtil;
import so.shanku.essential.utils.LogUtil;
import so.shanku.essential.utils.StringUtil;

import java.util.ArrayList;
import java.util.WeakHashMap;

/**
 * Created by Administrator on 2015/8/17 0017.
 */
public class MyApplication extends Application {
    private static MyApplication mInstance = null;

    private int screenWidth;// 屏幕的宽度
    private int screenHeight;

    private String tempUserAccount = "";  //访客登录

    public String getTempUserAccount() {
        return tempUserAccount;
    }

    public void setTempUserAccount(String tempUserAccount) {
        this.tempUserAccount = tempUserAccount;
    }

    /**
     * IP地址
     */
    private String ip = "";
    /**
     * 调用服务器接口获取服务器数据的工具
     */
    protected GetServicesDataUtil getDataUtil;

    public GetServicesDataUtil getGetDataUtil() {
        return getDataUtil;
    }

    public int getScreenWidth() {
        return screenWidth;
    }

    /**
     * 返回屏幕的宽度 数据在
     *
     * @param screenWidth
     */
    public void setScreenWidth(int screenWidth) {
        this.screenWidth = screenWidth;
    }

    public void setScreenHeight(int screenHeight) {
        this.screenHeight = screenHeight;
    }

    public int getScreenHeight() {
        return screenHeight;
    }

    /**
     * 存储下载过的图片
     */
    private WeakHashMap<String, Bitmap> bitmapHashMap = new WeakHashMap<String, Bitmap>();

    public WeakHashMap<String, Bitmap> getBitmapHashMap() {
        if (bitmapHashMap == null) {
            bitmapHashMap = new WeakHashMap<String, Bitmap>();
        }
        return bitmapHashMap;
    }

    public void addBitmapHashMap(String url, Bitmap bitmap) {
        bitmapHashMap.put(url, bitmap);
    }

    /**
     * 关注的店铺和商品
     */
    private ArrayList<JsonMap<String, Object>> collectionGoods = new ArrayList<JsonMap<String, Object>>();
    private ArrayList<JsonMap<String, Object>> attentionBrands = new ArrayList<JsonMap<String, Object>>();

    public ArrayList<JsonMap<String, Object>> getCollectionGoods() {
        return collectionGoods;
    }

    public void setCollectionGoods(
            ArrayList<JsonMap<String, Object>> collectionGoods) {
        this.collectionGoods = collectionGoods;
    }

    public ArrayList<JsonMap<String, Object>> getAttentionBrands() {
        return attentionBrands;
    }

    public void setAttentionBrands(ArrayList<JsonMap<String, Object>> attentionBrand) {
//        if (attentionBrand == null) {
//            this.attentionBrands.clear();
//        } else {
//            this.attentionBrands = attentionBrand;
//        }
    }

    /**
     * 添加关注的店铺
     *
     * @param vendorId
     */
    public void addAttendBrands(String vendorId) {
//        JsonMap jsonMap = new JsonMap<String, Object>();
//        jsonMap.put("id", vendorId);
//        if (attentionBrands == null) {
//            attentionBrands = new ArrayList<JsonMap<String, Object>>();
//        }
//        attentionBrands.add(jsonMap);
    }

    /**
     * 历史关注的品牌 是否包含
     *
     * @param id
     * @return
     */
    public boolean validateAttendBrands(String id) {

        for (JsonMap map : attentionBrands) {
            String idStr = map.getString("id");
            if (id.equals(idStr)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 移除 关注过的品牌
     *
     * @param id
     */
    public void removeAttendBrands(String id) {
        if (attentionBrands != null) {
            for (JsonMap map : attentionBrands) {
                if (id.equals(map.getString("id"))) {
                    attentionBrands.remove(map);
                    break;
                }
            }
        }
    }

    /**
     * 历史关注的品牌 是否包含
     *
     * @param id
     * @return
     */
    public boolean validateFavourteProduct(String id) {
        if (collectionGoods != null) {
            for (JsonMap map : collectionGoods) {
                String idStr = map.getString("ProductId");
                if (id.equals(idStr)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 移除 关注过的品牌
     *
     * @param id
     */
    public void removeFavourteProduct(String id) {
        if (collectionGoods != null) {
            for (JsonMap map : collectionGoods) {
                if (id.equals(map.getString("ProductId"))) {
                    collectionGoods.remove(map);
                    break;
                }
            }
        }
    }

    public static MyApplication getInstance() {
        if (mInstance == null) {
            mInstance = new MyApplication();
        }
        return mInstance;
    }

    /**
     * 未读消息数量
     */
    private int pushMsgCount = 0;

    public int getPushMsgCount() {
        return pushMsgCount;
    }

    public void setPushMsgCount(int pushMsgCount) {
        this.pushMsgCount = pushMsgCount;
    }

    /**
     * 购物车商品数量
     */
    private int shopcart_num = 0;

    public int getShopcart_num() {
        return shopcart_num;
    }

    public void setShopcart_num(int shopcart_num) {
        this.shopcart_num = shopcart_num;
    }

    public void addShopCartNum() {
        shopcart_num++;
    }

    // /**
    // * 购物车中的数据 没有登陆时
    // */
    // private List<JsonMap<String, Object>> shoppingCartNoUser;
    // /**
    // * 购物车中的数据 用户已登录
    // */
    // private List<JsonMap<String, Object>> shoppingCartHasUser;
    //
    // /**
    // * 购物车中的数据 没有登陆时
    // */
    // public List<JsonMap<String, Object>> getShoppingCartNoUser() {
    // if (null == this.shoppingCartNoUser) {
    // shoppingCartNoUser = new ArrayList<JsonMap<String, Object>>();
    // }
    // return shoppingCartNoUser;
    // }
    //
    // /**
    // * 购物车中的数据 用户已登录
    // */
    // public List<JsonMap<String, Object>> getShoppingCartHasUser() {
    // if (null == this.shoppingCartHasUser) {
    // shoppingCartHasUser = new ArrayList<JsonMap<String, Object>>();
    // }
    // return shoppingCartHasUser;
    // }
    //
    //
    // /**
    // * 添加购物车中的数据 没有登陆时
    // */
    // public void addShoppingCartNoUser(JsonMap<String, Object> data) {
    // if (null == this.shoppingCartNoUser) {
    // shoppingCartNoUser = new ArrayList<JsonMap<String, Object>>();
    // }
    // this.shoppingCartNoUser.add(data);
    // }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        MyCrashHandler crashHandler = MyCrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        initImageLoader(getApplicationContext());
        getDataUtil = GetServicesDataUtil.init();
        JPushInterface.setDebugMode(LogUtil.isDebug); // 设置开启日志,发布时请关闭日志
        com.umeng.socialize.utils.Log.LOG = LogUtil.isDebug;
        // Boolean hPushStatue = JPushInterface.getConnectionState(this);
        // if (!hPushStatue) {
        JPushInterface.init(this);
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(
                context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        // Remove for release app
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    BitmapUtils bitmapUtils;
    BitmapUtils loadUserHeadIconUtils;// 加载用户头像

    /**
     * 默认加载图片 显示加载失败的图像
     *
     * @return
     */
    public DisplayImageOptions getDefaultOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.pic_load_error)
                .showImageOnFail(R.drawable.pic_load_error).cacheInMemory(true)
                .cacheOnDisk(true).considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        return options;
    }

    /**
     * 店铺页 店铺背景
     *
     * @return
     */
    public DisplayImageOptions getShopBgOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.load_shopbg_error)
                .showImageOnFail(R.drawable.load_shopbg_error).cacheInMemory(true)
                .cacheOnDisk(true).considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        return options;
    }

    /**
     * 默认加载图片 显示加载失败的图像
     *
     * @return
     */
    public DisplayImageOptions getBrandDefaultOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.brand_log_load_error)
                .showImageOnFail(R.drawable.brand_log_load_error)
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        return options;
    }


    /**
     * 默认加载图片 显示加载失败的图像
     *
     * @return
     */
    public DisplayImageOptions getUserHeadOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.user_center)
                .showImageOnFail(R.drawable.user_center)
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        return options;
    }

    /**
     * @param @return
     * @param @throws Exception
     * @return String 返回类型
     * @throws
     * @Title: getVersionName
     * @Description: TODO作用：获取版本名称
     */
    public String getVersionName() {
        // 获取packagemanager的实例
        try {
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
                    0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "0.0";
        }
    }


    /**
     * 商品剩余个数提示
     *
     * @param view
     */
    public void startAnimation(View view) {
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.good_retain_anim);
        anim.setFillAfter(true);
        view.startAnimation(anim);
    }
    /**
     * 分享登录
     */
    // 添加微信、微信朋友圈平台
    // 注意：在微信授权的时候，必须传递appSecret
    // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
    /**
     * 微信AppID
     */
    public static final String WEIXIN_APP_ID = "wxa1561d1224f9f2bd";
    /**
     * 微信AppSecret
     */
    public static final String WEIXIN_APP_SECRET = "d6333fdb4602c5714bfa3471df515c1e";
    // 公共 qq的id和key
//	private String QQ_APP_ID = "100424468";
//	private String QQ_APP_Secret = "c7394704798a158208a74ab60104f0ba";
    // 添加QQ、QZone平台
    String QQ_APP_ID = "1104810961";
    String QQ_APP_Secret = "KJgrIKpj8yfxjyr6";
    UMSocialService mController = null;

    public UMSocialService getmController() {
        return mController;
    }


    public void showShareCompont(Activity activity, String imgUrl,
                                 String targetUrl, String shareTitle, String content) {
        targetUrl = GetDataConfing.Url_Base + targetUrl + "&type=1";
        LogUtil.d("MyApplication",targetUrl);
        if (null == mController) {
            mController = UMServiceFactory.getUMSocialService("com.oceanmall");

        }
        mController.getConfig().cleanListeners();
        // 添加腾讯微博SSO授权
        // mController.getConfig().setSsoHandler(new TencentWBSsoHandler());


        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(activity, WEIXIN_APP_ID,
                WEIXIN_APP_SECRET);
        wxHandler.addToSocialSDK();
        wxHandler.showCompressToast(false);
        // 支持微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(activity, WEIXIN_APP_ID,
                WEIXIN_APP_SECRET);
        // wxCircleHandler.showCompressToast(false);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();

        // 添加QQ支持, 并且设置QQ分享内容的target url
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(activity, QQ_APP_ID,
                QQ_APP_Secret);
        qqSsoHandler.setTargetUrl(targetUrl);
        qqSsoHandler.addToSocialSDK();
        // 添加QZone平台
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(activity,
                QQ_APP_ID, QQ_APP_Secret);
        qZoneSsoHandler.addToSocialSDK();
        if (TextUtils.isEmpty(shareTitle)) {
            shareTitle = getString(R.string.app_name);
        }

        if (TextUtils.isEmpty(content)) {
            content = shareTitle;//getString(R.string.share_default_content);
        }
        UMImage localImage;
        if (TextUtils.isEmpty(imgUrl)) {
            localImage = new UMImage(this, R.drawable.app_icon);
            localImage.setTitle(shareTitle);
            localImage.setTargetUrl(targetUrl);

        } else {
            imgUrl= StringUtil.getSSImage(imgUrl);
            localImage = new UMImage(this, imgUrl);
            localImage.setTitle(shareTitle);
            localImage.setTargetUrl(imgUrl);
        }

        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        //new SinaSsoHandler().addToSocialSDK();
        SinaShareContent sinaContent = new SinaShareContent();
        sinaContent.setShareContent(content+targetUrl);
        sinaContent.setTitle(shareTitle);
        sinaContent.setTargetUrl(targetUrl);
        sinaContent.setShareImage(localImage);
        mController.setShareMedia(sinaContent);

        // 微信分享必须设置targetURL，需要为http链接格式
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(content);
        weixinContent.setTitle(shareTitle);
        weixinContent.setTargetUrl(targetUrl);
        weixinContent.setShareImage(localImage);
        mController.setShareMedia(weixinContent);

        // 设置朋友圈分享的内容 只支持title
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(content);
        circleMedia.setTitle(content);
        circleMedia.setTargetUrl(targetUrl);
        circleMedia.setShareImage(localImage);
        mController.setShareMedia(circleMedia);

        // 设置QQ空间分享内容
        QZoneShareContent qzone = new QZoneShareContent();
        qzone.setShareContent(content);
        qzone.setTargetUrl(targetUrl);
        qzone.setTitle(shareTitle);
        qzone.setShareImage(localImage);
        mController.setShareMedia(qzone);

        QQShareContent qqShareContent = new QQShareContent();
        qqShareContent.setShareContent(content);
        qqShareContent.setTitle(shareTitle);
        qqShareContent.setShareImage(localImage);
        qqShareContent.setTargetUrl(targetUrl);
        mController.setShareMedia(qqShareContent);

        mController.getConfig().removePlatform(SHARE_MEDIA.TENCENT,
                SHARE_MEDIA.DOUBAN);

        // SinaShareContent sinaContent = new SinaShareContent();
        // sinaContent.setShareContent(content);
        // sinaContent.setTitle(title);
        // sinaContent.setShareImage(localImage);
        // mController.setShareMedia(sinaContent);

        mController.openShare(activity, false);
        SocializeListeners.SnsPostListener mSnsPostListener = new SocializeListeners.SnsPostListener() {

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int stCode,
                                   SocializeEntity entity) {

                if (stCode == 200) {
                    Toast.makeText(MyApplication.this, "分享成功",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MyApplication.this, "分享失败 " + stCode,
                            Toast.LENGTH_SHORT).show();
                }
            }
        };
        mController.registerListener(mSnsPostListener);

    }

    private UMSocialService mLoginController;

    public UMSocialService initThirdLogin(Activity activity) {
        mLoginController = UMServiceFactory
                .getUMSocialService("com.umeng.login");
        // 添加新浪SSO授权
        mLoginController.getConfig().setSsoHandler(new SinaSsoHandler());
//        mController.deleteOauth(activity, SHARE_MEDIA.SINA,
//                new SocializeListeners.SocializeClientListener() {
//                    @Override
//                    public void onStart() {
//                    }
//                    @Override
//                    public void onComplete(int status, SocializeEntity entity) {
//
//                    }
//                });
        // 添加腾讯微博SSO授权
        // mController.getConfig().setSsoHandler(new TencentWBSsoHandler());


        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(activity, WEIXIN_APP_ID,
                WEIXIN_APP_SECRET);
        wxHandler.addToSocialSDK();
        wxHandler.showCompressToast(false);
        wxHandler.setRefreshTokenAvailable(false);

        // 添加QQ支持, 并且设置QQ分享内容的target url
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(activity, QQ_APP_ID,
                QQ_APP_Secret);
        qqSsoHandler.addToSocialSDK();
        mLoginController.getConfig().removePlatform(SHARE_MEDIA.TENCENT,
                SHARE_MEDIA.DOUBAN);
        return mLoginController;
    }

    private String getLocationIP() {
        ConnectivityManager connectivity = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        String type = info[i].getTypeName();
                        if (type.equalsIgnoreCase("WIFI")) {
                            // 获取wifi服务
                            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                            // 判断wifi是否开启
                            if (!wifiManager.isWifiEnabled()) {
                                wifiManager.setWifiEnabled(true);
                            }
                            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                            int ipAddress = wifiInfo.getIpAddress();
                            ip = intToIp(ipAddress);
                        } else if (type.equalsIgnoreCase("MOBILE")) {
                            ip = NetWorkHelper.GetHostIp();
                        }
                    }
        }

        return TextUtils.isEmpty(ip)?"127.0.0.1":ip;
    }

    public String getIP() {
        return TextUtils.isEmpty(ip) ? getLocationIP() : ip;
    }

    /**
     * @param @param  i
     * @param @return
     * @return String 返回类型
     * @throws
     * @Title: intToIp
     * @Description: TODO作用：WIFI IP
     */
    private String intToIp(int i) {

        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + (i >> 24 & 0xFF);
    }


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        LogUtil.d("memory onTrimMemory", level + "");
    }

    private float density;

    public float getScreenDensity() {
        return density;
    }

    public void setScreenDensity(float density) {
        this.density = density;
    }
}
